package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.product.pojo.dto.FilterAttrOnOffJXCDTO;
import com.xbongbong.pro.product.pojo.vo.FilterAttrOnOffJXCVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.RefundDao;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.dictionary.ReturnStatusEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.RefundSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import com.xbongbong.sys.model.CompanyConfigModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/3/22 15:07
 * @since v1.0
 */
@Service("refundModel")
public class RefundModelImpl implements RefundModel {

    @Resource
    private RefundDao refundDao;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private RefundSubDataModel refundSubDataModel;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private InstockModel instockModel;

    private static final List<String> selectProductAttrList = Arrays.asList(SelectProductEnum.BATCH.getAttr(), SelectProductEnum.GUARANTEE_PERIOD.getAttr(), SelectProductEnum.PRODUCE_DATE.getAttr(), SelectProductEnum.EXPIRE_DATE.getAttr());

    private static final List<String> stockNumAttrList = Arrays.asList(SelectProductEnum.SOURCE_DOC.getAttr(), SelectProductEnum.INSTOCK_NUM.getAttr(), SelectProductEnum.WAIT_INSTOCK_NUM.getAttr());

    /**
     * 退货退款单数据单条查询
     *
     * @param key    主键ID
     * @param corpid 公司ID
     * @return Integer
     * @author feng.zheng
     * @date 2019/2/15 20:27
     * @since v1.0
     */
    @Override
    public RefundEntityExt getByKey(Long key, String corpid) {
        RefundEntityExt entityExt = refundDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        return entityExt;
    }

    /**
     * 插入
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer insert(RefundEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = refundDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        return success;
    }

    /**
     * 更新
     *
     * @param entity 实体
     * @return 是否成功
     * @throws XbbException 数据库操作异常
     */
    @Override
    public Integer update(RefundEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = refundDao.update(entity);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = refundDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public Integer update(RefundEntityExt refundEntityExt, boolean isSaveSub) throws XbbException {
        if (isSaveSub) {
            return update(refundEntityExt);
        } else {
            long now = DateUtil.getInt();
            refundEntityExt.setUpdateTime(now);
            paasFormSubDataModel.transferSubForm(refundEntityExt, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
            StandardizeDataUtil.standardizeNotString(refundEntityExt);
            Integer success = refundDao.update(refundEntityExt);

            if (Objects.equals(1, success)) {
                // 更新时间
                success = refundDao.updateTime(now + 1, refundEntityExt.getId(), refundEntityExt.getCorpid());
                // 更新es
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(refundEntityExt, paasFormDataEntity);
                InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND);
                insertDTO.getSource().remove("creatorId");
                paasEsModel.update(insertDTO);
            }

            return success;
        }
    }


    /**
     * 查找
     *
     * @param param 查询条件
     * @return 实体集合
     */
    @Override
    public List<RefundEntityExt> findEntitys(Map<String, Object> param) {
        List<RefundEntityExt> entitys = refundDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        }
        return entitys;
    }

    /**
     * 获取符合查询条件的记录总数
     *
     * @param param 查询条件
     * @return 符合查询条件的记录总数
     */
    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return refundDao.getEntitysCount(param);
    }

    /**
     * 保存
     *
     * @param refundEntityExt 退货退款单实体
     * @return Integer
     * @author feng.zheng
     * @date 2019/1/23 20:27
     * @since v1.0
     */
    @Override
    public Integer save(RefundEntityExt refundEntityExt) throws XbbException {
        if(refundEntityExt.getId() == null || refundEntityExt.getId().equals(0L)) {
            return insert(refundEntityExt);
        }
        return update(refundEntityExt);
    }

    @Override
    public Integer save(RefundEntityExt refundEntityExt, boolean isSaveSub) throws XbbException {
        if(refundEntityExt.getId() == null || refundEntityExt.getId().equals(0L)) {
            return insert(refundEntityExt);
        }
        return update(refundEntityExt, isSaveSub);
    }


    /**
     * 批量删除
     *
     * @param idList 数据id列表
     * @param corpid 公司id
     * @param del    删除标识
     * @throws XbbException 异常
     */
    @Override
    public Integer deleteBatch(List<Long> idList, String corpid, Integer del) throws XbbException {
        Integer integer = refundDao.deleteBatch(idList, corpid);
        paasEsModel.deleteBatch(idList, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_REFUND);

        paasFormSubDataModel.deleteBatchByDataId(idList, corpid, IndexTypeEnum.IDX_SAAS_REFUND_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key, String corpid) throws XbbException {
        Integer integer = refundDao.deleteByKey(key, corpid);
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid + "_" + key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        return integer;
    }

    @Override
    public List<String> getCorpids() throws XbbException {
        return refundDao.getCorpids();
    }

    /**
     * 批量更新
     *
     * @param list   数据列表 格式：[{"corpid": "", "id": "", "data":[{"key": "", "value": ""}]}]
     * @param corpid 公司id
     * @return Integer
     * @throws XbbException XbbException
     */
    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = refundDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_REFUND);
        }
        if (!subList.isEmpty()) {
            refundSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> list, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = refundDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_REFUND, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            refundSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        StandardizeDataUtil.standardizeList(updateList);
        Integer integer = refundDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_REFUND, needThrow);
        return integer;
    }

    @Override
    public Integer updateBatchImmediately(List<UpdateDataEntity> list, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(list);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(list);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(list)) {
            StandardizeDataUtil.standardizeList(list);
            integer = refundDao.updateBatch(list, corpid);
            paasEsModel.updateBatchMuchField(list, IndexTypeEnum.IDX_SAAS_REFUND, WriteRequest.RefreshPolicy.NONE);
        }
        if (!subList.isEmpty()) {
            refundSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List<RefundEntityExt> findEntitysWithoutSub(Map<String, Object> param) {
        return refundDao.findEntitys(param);
    }

    @Override
    public Integer deleteByKey4Process(Long key, String corpid) throws XbbException {
        RefundEntityExt refundEntityExt = new RefundEntityExt();
        refundEntityExt.setId(key);
        refundEntityExt.setCorpid(corpid);
        refundEntityExt.setDel(DelEnum.INVALID.getDel());
        Integer integer = refundDao.update(refundEntityExt);
        // 更改成作废的del状态
        InsertDTO insertDTO = new InsertDTO();
        insertDTO.setEsId(corpid + "_" + key);
        Map<String,Object> map = new HashMap<>(16);
        map.put("del",DelEnum.INVALID.getDel());
        map.put("updateTime",DateTimeUtil.getInt());
        JSONObject object = new JSONObject();
        object.put(ReturnEnum.ORDER_STATUS.getAttr(), ReturnStatusEnum.ABOLISHED.getCode());
        map.put(StringConstant.JSON_DATA, object);
        insertDTO.setSource(map);
        insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_REFUND);
        paasEsModel.update(insertDTO);
        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
        return integer;
    }

    @Override
    public FilterAttrOnOffJXCVO filterAttrOnOffJXC(FilterAttrOnOffJXCDTO filterAttrOnOffJXCDTO) throws XbbException {
        FilterAttrOnOffJXCVO filterAttrOnOffJXCVO = new FilterAttrOnOffJXCVO();
        // 是否开启进销存
        Boolean enableJxc = filterAttrOnOffJXCDTO.getEnableJxc();
        Boolean isJxcUse = enableJxc;
        if (Objects.isNull(enableJxc)) {
            isJxcUse = paasAppModel.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), filterAttrOnOffJXCDTO.getCorpid());
        }
        List<FieldAttrEntity> headList = filterAttrOnOffJXCDTO.getFieldAttrEntityList();
        Integer operatePageCode = filterAttrOnOffJXCDTO.getOperatePageCode();
        if (!isJxcUse){
            // 进销存没有开启
            if (Objects.equals(operatePageCode, OperatePageEnum.DESIGN.getCode())) {
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.PRODUCTS.getAttr())) {
                        List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                        for (FieldAttrEntity entity : items) {
                            if (selectProductAttrList.contains(entity.getAttr()) || stockNumAttrList.contains(entity.getAttr())) {
                                entity.setEditHide(1);
                            }
                        }
                    }
                }
            } else {
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.PRODUCTS.getAttr())) {
                        List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                        items.removeIf(entity -> selectProductAttrList.contains(entity.getAttr()) || stockNumAttrList.contains(entity.getAttr()));
                    }
                }
            }
        } else {
            if (Objects.equals(operatePageCode, OperatePageEnum.DESIGN.getCode())) {
                Boolean batchShelf = companyConfigModel.getBatchShelf(filterAttrOnOffJXCDTO.getCorpid());
                for (FieldAttrEntity fieldAttrEntity : headList) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), RefundEnum.PRODUCTS.getAttr())) {
                        List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                        for (FieldAttrEntity entity : items) {
                            if ((batchShelf && selectProductAttrList.contains(entity.getAttr())) || stockNumAttrList.contains(entity.getAttr()))  {
                                entity.setEditHide(0);
                            }
                        }
                    }
                }


            }
        }
        return filterAttrOnOffJXCVO;
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     * @author long.rao
     * @date 2019-02-13 20:53
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> entities = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        Integer fromCopy = BasicConstant.ZERO;
        if(formatExplainDTO.getSaasSpecialParamPojo() != null){
            // true: 复制1 false：编辑0
            fromCopy = Objects.equals(formatExplainDTO.getSaasSpecialParamPojo().getFromCopy(), 1) ? BasicConstant.ONE : BasicConstant.ZERO;
        }
        FilterAttrOnOffJXCDTO filterAttrOnOffJXCDTO = new FilterAttrOnOffJXCDTO();
        BeanUtil.copyProperties(formatExplainDTO, filterAttrOnOffJXCDTO);
        filterAttrOnOffJXCDTO.setFieldAttrEntityList(formatExplainDTO.getExplainList());
        filterAttrOnOffJXCDTO.setOperatePageCode(OperatePageEnum.EDIT.getCode());
        filterAttrOnOffJXC(filterAttrOnOffJXCDTO);
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        boolean unitNoEdit = false;
        if (Objects.nonNull(dataEntity) && !Objects.equals(formatExplainDTO.getFromCopy(), true)) {
            if (CollectionUtils.isEmpty(dataEntity.getData().getJSONArray(RefundEnum.INSTOCK_ID.getAttr()))) {
                //校验审批中是否有下游入库单
                if (commonHelp.isOpenWorkFlow(corpid)) {
                    List<PaasFormDataEntityExt> approvalPaasFormDataList = instockModel.findInstockList(corpid, InstockTypeEnum.RED_CONTRACT_INSTOCK.getCode(), dataEntity.getId(),
                            Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()), Arrays.asList(FieldTypeEnum.DATAID.getAlias()));
                    if (!approvalPaasFormDataList.isEmpty()) {
                        unitNoEdit = true;
                    }
                } else {
                    List<PaasProcessRelatedDataEntity> paasProcessRelatedDataEntities = paasProcessRelatedDataModel.getByRefIdAndBusinessType(dataEntity.getId(), XbbRefTypeEnum.REFUND_INSTOCK.getCode(), corpid);
                    if (!paasProcessRelatedDataEntities.isEmpty()) {
                        unitNoEdit = true;
                    }
                }
            }else{
                unitNoEdit = true;
            }
        }
        for (FieldAttrEntity fieldAttrEntity : entities) {
            String attr = fieldAttrEntity.getAttr();
            if (Objects.equals(attr, RefundEnum.CUSTOMER_ID.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.REFUND_NO.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.CONTRACT_ID.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.PRODUCTS.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                if (!Objects.isNull(formatExplainDTO.getDataEntity().getData().get(RefundEnum.INSTOCK_ID.getAttr())) && !formatExplainDTO.getDataEntity().getData().getJSONArray(RefundEnum.INSTOCK_ID.getAttr()).isEmpty()){
                    List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                    subExplainList.forEach(item -> item.setEditable(0));
                    fieldAttrEntity.getSubForm().setItems(subExplainList);
                }
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.REFUND, corpid, BasicConstant.ONE, unitNoEdit);
            } else if (Objects.equals(attr, RefundEnum.RETURN_AMOUNT.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.INVOICES.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.PAYMENT_SHEETS.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(attr, RefundEnum.PAYMENTS.getAttr()) && Objects.equals(fromCopy, BasicConstant.ZERO)) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    /**
     * 编辑时将获取数据格式化
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result              要返回的jsonobject
     * @throws XbbException 业务异常
     * @author feng.zheng
     * @date 2019/1/22 15:28
     */
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, RefundEnum.CUSTOMER_ID.getAttr(), RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), RefundEnum.CUSTOMER_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, RefundEnum.CONTRACT_ID.getAttr(), RefundEnum.CONTRACT_ID_LINKED_TEXT.getAttr(), RefundEnum.CONTRACT_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, RefundEnum.PAYMENT_SHEETS.getAttr(), RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENT_SHEETS.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, RefundEnum.INVOICES.getAttr(), RefundEnum.INVOICES_LINKED_TEXT.getAttr(), RefundEnum.INVOICES.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, RefundEnum.PAYMENTS.getAttr(), RefundEnum.PAYMENTS_LINKED_TEXT.getAttr(), RefundEnum.PAYMENTS.getFieldType());

        // 格式化关联产品
//        formatProduct4Show(result, saasAnalysisDataDTO);
    }

    /**
     * 手动拼装conProductList，以便于回显
     * @param corpid
     * @param conProductList
     * @param productArray
     * @param productMap
     * @throws XbbException
     */
    @Override
    public void getProductList(String corpid, List<ContractProductEntity> conProductList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                Double cost = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                // 兼容一下之前的脏数据吧。我也很绝望
                Double price = getDoubleOrDefaultFromFormData(productObject, ProductEnum.PRICE.getAttr(), 0D);
                if (!Objects.equals(FastJsonHelper.getStringFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCT_PRICE.getSaasAttr()), StringConstant.INVISIBLE_VALUE)) {
                    price = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCT_PRICE.getSaasAttr(), 0D);
                }
                ContractProductEntity productEntity = new ContractProductEntity();
                productEntity.setBarcode(barcode);
                productEntity.setProductUnit(unit);
                productEntity.setCorpid(corpid);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setSpecification(specification);
                productEntity.setCost(cost);
                productEntity.setMemo(memo);
                productEntity.setSort(sort);
                productEntity.setPrice(price);
                /*JSONObject jsonObject = new JSONObject();
                jsonObject.put(RefundProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(RefundProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(RefundProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(RefundProductEnum.PRICE.getAttr(), price);
                jsonObject.put(RefundProductEnum.SUBTOTAL.getAttr(), price * productNum);
                jsonObject.put(RefundProductEnum.MEMO.getAttr(), memo);
                productEntity.setData(jsonObject);*/
                conProductList.add(productEntity);
            }
        }
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<ContractProductEntity> conProductList = new ArrayList<>();
        Map<Long, JSONArray> refProductSeqMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

        Long redContractId = null;
        if (Objects.nonNull(dataId) && !Objects.equals(0L, dataId)) {
            RefundEntityExt refundEntityExt = getByKey(dataId,corpid);
            // 工作流的审批，红冲合同未生成
            redContractId = refundEntityExt.getData().getLong(RefundEnum.RED_CONTRACT_ID.getAttr());

        }
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L) || Objects.isNull(redContractId)) {
            if (data.get(RefundEnum.PRODUCTS.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, RefundEnum.PRODUCTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, conProductList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(RefundEnum.PRODUCTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        ContractProductEntity contractProductEntity = new ContractProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            contractProductEntity.setId(subProductId);
                        }
                        contractProductEntity.setData(jsonObject);
                        conProductList.add(contractProductEntity);
                    }
                }
            }
        } else {

            conProductList = contractProductModel.getProductsByConId(redContractId,corpid);
            // 表单序列号流水
            List<ProductSerialFlowEntity> productSerialFlowList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), XbbRefTypeEnum.REFUND.getCode(), corpid);



            for (ProductSerialFlowEntity entity : productSerialFlowList) {
                JSONArray serialArray = refProductSeqMap.getOrDefault(entity.getRefProductId(), new JSONArray());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(SerialEnum.SERIAL.getAttr(), entity.getSeq());
                jsonObject.put(SerialEnum.MEMO.getAttr(), entity.getMemo());
                serialArray.add(jsonObject);

                refProductSeqMap.put(entity.getRefProductId(), serialArray);
            }
            conProductList.forEach(item -> {
                JSONArray seqArray = refProductSeqMap.getOrDefault(item.getId(), null);
                if (Objects.nonNull(seqArray)) {
                    item.getData().put(ProductConstant.SEQ, seqArray);
                }
            });
        }

        JSONArray productArray = new JSONArray();
        for (ContractProductEntity contractProductEntity : conProductList){
            JSONObject json = contractProductEntity.getData();
            Double rate = showFormatHelp.approvalSetBusinessUnit(json, contractProductEntity);
            if (Objects.isNull(json) || json.isEmpty()){
                json = new JSONObject();
                for (RefundProductEnum refundProductEnum : RefundProductEnum.values()){
                    String attr = refundProductEnum.getAttr();
                    switch (refundProductEnum){
                        case PRODUCT:
                            json.put(attr,contractProductEntity.getProductId());
                            break;
                        case COST:
                            // TODO 销售出库单上的产品出库成本
                            json.put(attr, 0);
                            break;
                        case PRICE:
                            json.put(attr,contractProductEntity.getPrice());
                            break;
                        case NUM:
                            json.put(attr,Math.abs(contractProductEntity.getProductNum()));
                            break;
                        case MEMO:
                            json.put(attr,contractProductEntity.getMemo());
                            break;
                        case SUBTOTAL:
                            json.put(attr,Math.abs(contractProductEntity.getProductNum() * contractProductEntity.getPrice()));
                            break;
                        case UNIT:
                            json.put(attr, contractProductEntity.getProductUnit());
                            break;
                        default:
                            break;
                    }
                }
            }else {
                JSONObject refundBatch = new JSONObject();
                refundBatch.put("text", json.getString(SelectProductEnum.BATCH.getAttr()));
                refundBatch.put("value", json.getString(SelectProductEnum.BATCH.getAttr()));
                json.put(RefundProductEnum.BATCH.getAttr(), refundBatch);
            }
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,contractProductEntity.getId());
                if (Objects.isNull(contractProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(contractProductEntity.getCorpid(),contractProductEntity.getProductUnit()));
            }
            // 源单编号字段，移动端顶部渲染需要
            if (json.containsKey(SelectProductEnum.SOURCE_DOC.getAttr())) {
                json.put(SelectProductEnum.SOURCE_SOURCE_DOC.getAttr(), json.get(SelectProductEnum.SOURCE_DOC.getAttr()));
            }
            json.put("refId",contractProductEntity.getId());
            productArray.add(json);

            // 产品是否开启序列号, 审批详情也会走到这里，所以做个空指针校验
            ProductEntityExt productEntityExt = productModel.getByKey(json.getLongValue(RefundProductEnum.PRODUCT.getAttr()), corpid);

            if (Objects.nonNull(productEntityExt)) {
                JSONObject productData = productEntityExt.getData();
                json.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), productData.getLongValue(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()));
            }
            json.put("editableSerial", 1);
        }
        data.put(RefundEnum.PRODUCTS.getAttr(),productArray);
    }

    @Override
    public void formatDataForDistributor(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
        showFormatHelp.formatLinkBusiness4Show(result, ReturnEnum.LINK_DISTRIBUTOR.getAttr(), ReturnEnum.LINK_DISTRIBUTOR_LINKED_TEXT.getAttr(), ReturnEnum.LINK_DISTRIBUTOR.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnEnum.ORDER_ID.getAttr(), ReturnEnum.ORDER_ID_LINKED_TEXT.getAttr(), ReturnEnum.ORDER_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnEnum.PAYMENT_SHEETS.getAttr(), ReturnEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENT_SHEETS.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnEnum.INVOICES.getAttr(), ReturnEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnEnum.INVOICES.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnEnum.PAYMENTS.getAttr(), ReturnEnum.PAYMENTS_LINKED_TEXT.getAttr(), ReturnEnum.PAYMENTS.getFieldType());
    }

    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = refundDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_REFUND);
        paasEsModel.update(insertDTO);
        return success;
    }
}
